package com.system.enterprisemanagementsystem.controller;

import com.system.enterprisemanagementsystem.pojo.Emp;
import com.system.enterprisemanagementsystem.pojo.Result;
import com.system.enterprisemanagementsystem.service.EmpService;
import com.system.enterprisemanagementsystem.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;


@Slf4j
@RestController
public class LoginController {


    @Autowired
    EmpService empService;

    @PostMapping("/login")
    public Result login(@RequestBody Emp emp) {
        //1、先去验证账号、密码是否正确
        Emp user = empService.login(emp.getUsername(), emp.getPassword());
        if (user != null) {
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", user.getId());
            claims.put("username", user.getUsername());
            claims.put("name", user.getName());

            //生成token
            String token = JwtUtils.generateToken(claims);

            //构造响应数据
            Map<String, Object> data = new HashMap<>();
            data.put("id", user.getId());
            data.put("username", user.getUsername());
            data.put("name", user.getName());
            data.put("token", token);

            return Result.success(data);
        } else {
            return Result.error("用户名或密码错误");
        }

    }

}
